#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Mikan WSGI 開発 サーバ 機能

Mikan Python Web Framework
"""

__author__ = "K.Sonohara"
__status__ = "develop"
__version__ = "0.0.0_b"
__date__    = "2013/03/24"
__license__ = 'LGPL'

# ------------------------------------------------------------
## インポート
# ------------------------------------------------------------
# Ptyhon
import sys
sys.path.append("app")
sys.path.append("src")
import argparse

# ESiPC
from esipc import ESiPCProperty

# WSGI
from wsgiref.simple_server import WSGIServer, make_server

# Mikan
from mikan.wsgi import MikanWSGIWebapp

# ------------------------------------------------------------
## 変数
# ------------------------------------------------------------

# TODO リロード機能
reloading = True

# ------------------------------------------------------------
## 関数
# ------------------------------------------------------------

# ------------------------------------------------------------
## クラス
# ------------------------------------------------------------
class MikanThreadingWSGIServer(WSGIServer):
#class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
	pass

class MikanWSGIServer(object):
	def __init__(self, webapp_class=MikanWSGIWebapp, hostname='0.0.0.0', hostport=8000, forever=True):
		self.FWebappClass = webapp_class
		self.FHostName = hostname
		self.FHostPort = hostport
		self.FForever = forever

	def get_forever(self):
		return self.FForever

	def get_webapp_class(self):
		return self.FWebappClass

	def get_host_name(self):
		return self.FHostName

	def get_host_port(self):
		return self.FHostPort

	def __call__(self):
		mikan_root="."
		mikan_config=mikan_root + "/etc"

		webapp = self.webappclass(False, mikan_root=".", mikan_config=mikan_config)
		ws = make_server(self.hostname, self.hostport, webapp.invoke(), MikanThreadingWSGIServer)

		if self.forever:
			ws.serve_forever()
		else:
			ws.handle_request()

	# ----------------------------------------------------
	## Property
	forever = ESiPCProperty(get_forever, None, None)
	webappclass = ESiPCProperty(get_webapp_class, None, None)
	hostname = ESiPCProperty(get_host_name, None, None)
	hostport = ESiPCProperty(get_host_port, None, None)


# ------------------------------------------------------------
## メイン関数
# ------------------------------------------------------------
if __name__ == '__main__':
#	MikanWSGIServer()()
	parser = argparse.ArgumentParser(description='Mikan WSGI server.')
	parser.add_argument("-r", "--request", action='store_true', help='handle_request(). one request.')

	args = parser.parse_args()
	MikanWSGIServer(forever=not args.request)()

# ------------------------------------------------------------
